using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace SmartMedical.WinUI
{
    /// <summary>
    /// 选病人窗体
    /// 用于显示当前挂号的病人列表，支持按卡号查询
    /// </summary>
    public partial class SelectPatientForm : Form
    {
        #region 私有字段
        /// <summary>
        /// HTTP客户端，用于调用后端API
        /// </summary>
        private readonly HttpClient _httpClient;
        
        /// <summary>
        /// API基础URL - 读API端口（查询功能在读API中）
        /// </summary>
        private const string API_BASE_URL = "http://localhost:5043";
        
        /// <summary>
        /// 当前页码
        /// </summary>
        private int _currentPage = 1;
        
        /// <summary>
        /// 每页显示数量
        /// </summary>
        private const int PAGE_SIZE = 20;
        
        /// <summary>
        /// 总页数
        /// </summary>
        private int _totalPages = 1;
        
        /// <summary>
        /// 选中的挂号记录
        /// </summary>
        public RegistrationDto? SelectedRegistration { get; private set; }
        #endregion
        
        #region 构造函数
        /// <summary>
        /// 初始化选病人窗体
        /// </summary>
        public SelectPatientForm()
        {
            InitializeComponent();
            
            // 初始化HTTP客户端
            _httpClient = new HttpClient();
            _httpClient.Timeout = TimeSpan.FromSeconds(30);
            
            // 初始化窗体
            InitializeForm();
        }
        #endregion
        
        #region 初始化方法
        /// <summary>
        /// 初始化窗体设置
        /// </summary>
        private void InitializeForm()
        {
            this.Text = "选择病人";
            this.Size = new Size(1200, 700);
            this.StartPosition = FormStartPosition.CenterParent;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            
            // 设置DataGridView样式
            SetupDataGridView();
            
            // 加载数据
            LoadRegistrationData();
        }
        
        /// <summary>
        /// 设置DataGridView样式和列
        /// </summary>
        private void SetupDataGridView()
        {
            // 基本设置
            dgvRegistrations.AutoGenerateColumns = false;
            dgvRegistrations.AllowUserToAddRows = false;
            dgvRegistrations.AllowUserToDeleteRows = false;
            dgvRegistrations.ReadOnly = true;
            dgvRegistrations.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgvRegistrations.MultiSelect = false;
            dgvRegistrations.BackgroundColor = Color.White;
            dgvRegistrations.BorderStyle = BorderStyle.Fixed3D;
            dgvRegistrations.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            dgvRegistrations.RowHeadersVisible = false;
            
            // 添加列
            dgvRegistrations.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "RegistrationNo",
                HeaderText = "挂单号",
                DataPropertyName = "RegistrationNo",
                Width = 120,
                ReadOnly = true
            });
            
            dgvRegistrations.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "CardNo",
                HeaderText = "卡号",
                DataPropertyName = "CardNo",
                Width = 100,
                ReadOnly = true
            });
            
            dgvRegistrations.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "PatientName",
                HeaderText = "患者姓名",
                DataPropertyName = "PatientName",
                Width = 100,
                ReadOnly = true
            });
            
            dgvRegistrations.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "RegistrationType",
                HeaderText = "号类",
                DataPropertyName = "RegistrationType",
                Width = 80,
                ReadOnly = true
            });
            
            dgvRegistrations.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "RegistrationFee",
                HeaderText = "挂单费",
                DataPropertyName = "RegistrationFee",
                Width = 80,
                ReadOnly = true,
                DefaultCellStyle = new DataGridViewCellStyle { Format = "C2" }
            });
            
            dgvRegistrations.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "OtherFee",
                HeaderText = "其他费",
                DataPropertyName = "OtherFee",
                Width = 80,
                ReadOnly = true,
                DefaultCellStyle = new DataGridViewCellStyle { Format = "C2" }
            });
            
            dgvRegistrations.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "Department",
                HeaderText = "科室",
                DataPropertyName = "Department",
                Width = 120,
                ReadOnly = true
            });
            
            dgvRegistrations.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "Doctor",
                HeaderText = "医师",
                DataPropertyName = "Doctor",
                Width = 100,
                ReadOnly = true
            });
            
            dgvRegistrations.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "RegistrationDate",
                HeaderText = "挂号日期",
                DataPropertyName = "RegistrationDate",
                Width = 120,
                ReadOnly = true,
                DefaultCellStyle = new DataGridViewCellStyle { Format = "yyyy-MM-dd" }
            });
            
            dgvRegistrations.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "VisitDate",
                HeaderText = "就诊日期",
                DataPropertyName = "VisitDate",
                Width = 120,
                ReadOnly = true,
                DefaultCellStyle = new DataGridViewCellStyle { Format = "yyyy-MM-dd" }
            });
            
            dgvRegistrations.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "Status",
                HeaderText = "状态",
                DataPropertyName = "Status",
                Width = 80,
                ReadOnly = true
            });
        }
        #endregion
        
        #region 数据加载方法
        /// <summary>
        /// 加载挂号记录数据
        /// </summary>
        private async void LoadRegistrationData()
        {
            try
            {
                // 显示加载状态
                lblStatus.Text = "正在加载数据...";
                btnSearch.Enabled = false;
                btnSelect.Enabled = false;
                btnCancel.Enabled = false;
                
                // 构建查询参数
                var cardNo = txtCardNo.Text.Trim();
                var queryParams = new List<string>
                {
                    $"pageIndex={_currentPage}",
                    $"pageSize={PAGE_SIZE}"
                };
                
                if (!string.IsNullOrEmpty(cardNo))
                {
                    queryParams.Add($"cardNo={Uri.EscapeDataString(cardNo)}");
                }
                
                var queryString = string.Join("&", queryParams);
                var url = $"{API_BASE_URL}/api/Medical/GetRegistrationList?{queryString}";
                
                // 调用API
                try
                {
                    var response = await _httpClient.GetAsync(url);
                    
                    if (response.IsSuccessStatusCode)
                    {
                        var jsonContent = await response.Content.ReadAsStringAsync();
                        var apiResult = JsonConvert.DeserializeObject<ApiPagingResult<RegistrationDto>>(jsonContent);
                        
                        if (apiResult != null && apiResult.PageDatas != null)
                        {
                            // 绑定数据到DataGridView
                            dgvRegistrations.DataSource = apiResult.PageDatas;
                            
                            // 计算总页数
                            _totalPages = (int)Math.Ceiling((double)apiResult.TotalCount / PAGE_SIZE);
                            UpdatePaginationControls();
                            
                            lblStatus.Text = $"共找到 {apiResult.TotalCount} 条记录";
                        }
                        else
                        {
                            dgvRegistrations.DataSource = null;
                            lblStatus.Text = "未找到挂号记录";
                        }
                    }
                    else
                    {
                        MessageBox.Show($"获取数据失败：{response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        lblStatus.Text = "数据加载失败";
                    }
                }
                catch (HttpRequestException)
                {
                    // 如果API不可用，使用模拟数据进行测试
                    LoadMockData();
                }
            }
            catch (HttpRequestException ex)
            {
                MessageBox.Show($"网络请求失败：{ex.Message}", "网络错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                lblStatus.Text = "网络连接失败";
            }
            catch (TaskCanceledException)
            {
                MessageBox.Show("请求超时，请检查网络连接", "超时错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                lblStatus.Text = "请求超时";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                lblStatus.Text = "数据加载失败";
            }
            finally
            {
                // 恢复控件状态
                btnSearch.Enabled = true;
                btnSelect.Enabled = dgvRegistrations.SelectedRows.Count > 0;
                btnCancel.Enabled = true;
            }
        }
        
        /// <summary>
        /// 加载模拟数据（用于测试）
        /// </summary>
        private void LoadMockData()
        {
            try
            {
                // 创建模拟数据
                var mockData = new List<RegistrationDto>
                {
                    new RegistrationDto
                    {
                        Id = 1,
                        PatientId = 1001,
                        RegistrationNo = "GH202412010001",
                        CardNo = "20001",
                        PatientName = "张三",
                        RegistrationType = "普通号",
                        RegistrationFee = 10.00m,
                        OtherFee = 5.00m,
                        Department = "内科",
                        Doctor = "李医生",
                        RegistrationDate = DateTime.Now.AddDays(-1),
                        VisitDate = DateTime.Now,
                        Status = "已挂号",
                        IsEnable = true
                    },
                    new RegistrationDto
                    {
                        Id = 2,
                        PatientId = 1002,
                        RegistrationNo = "GH202412010002",
                        CardNo = "20002",
                        PatientName = "李四",
                        RegistrationType = "专家号",
                        RegistrationFee = 50.00m,
                        OtherFee = 10.00m,
                        Department = "妇科",
                        Doctor = "王医生",
                        RegistrationDate = DateTime.Now,
                        VisitDate = DateTime.Now.AddDays(1),
                        Status = "已挂号",
                        IsEnable = true
                    },
                    new RegistrationDto
                    {
                        Id = 3,
                        PatientId = 1003,
                        RegistrationNo = "GH202412010003",
                        CardNo = "20003",
                        PatientName = "王五",
                        RegistrationType = "普通号",
                        RegistrationFee = 10.00m,
                        OtherFee = 5.00m,
                        Department = "外科",
                        Doctor = "赵医生",
                        RegistrationDate = DateTime.Now,
                        VisitDate = DateTime.Now,
                        Status = "就诊中",
                        IsEnable = true
                    },
                    new RegistrationDto
                    {
                        Id = 4,
                        PatientId = 1004,
                        RegistrationNo = "GH202412010004",
                        CardNo = "20004",
                        PatientName = "赵六",
                        RegistrationType = "急诊号",
                        RegistrationFee = 20.00m,
                        OtherFee = 15.00m,
                        Department = "急诊科",
                        Doctor = "陈医生",
                        RegistrationDate = DateTime.Now,
                        VisitDate = DateTime.Now,
                        Status = "就诊中",
                        IsEnable = true
                    },
                    new RegistrationDto
                    {
                        Id = 5,
                        PatientId = 1001,
                        RegistrationNo = "GH202412010005",
                        CardNo = "20001",
                        PatientName = "张三",
                        RegistrationType = "专家号",
                        RegistrationFee = 50.00m,
                        OtherFee = 10.00m,
                        Department = "心内科",
                        Doctor = "刘医生",
                        RegistrationDate = DateTime.Now,
                        VisitDate = DateTime.Now.AddDays(2),
                        Status = "已挂号",
                        IsEnable = true
                    }
                };
                
                // 根据卡号过滤数据
                var cardNo = txtCardNo.Text.Trim();
                if (!string.IsNullOrEmpty(cardNo))
                {
                    mockData = mockData.Where(x => x.CardNo.Contains(cardNo)).ToList();
                }
                
                // 绑定数据到DataGridView
                dgvRegistrations.DataSource = mockData;
                
                // 更新分页信息
                _totalPages = 1;
                UpdatePaginationControls();
                
                lblStatus.Text = $"共找到 {mockData.Count} 条记录（模拟数据）";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载模拟数据失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                lblStatus.Text = "数据加载失败";
            }
        }
        
        /// <summary>
        /// 更新分页控件状态
        /// </summary>
        private void UpdatePaginationControls()
        {
            lblPageInfo.Text = $"第 {_currentPage} 页，共 {_totalPages} 页";
            btnPrevPage.Enabled = _currentPage > 1;
            btnNextPage.Enabled = _currentPage < _totalPages;
        }
        #endregion
        
        #region 事件处理方法
        /// <summary>
        /// 搜索按钮点击事件
        /// </summary>
        private void BtnSearch_Click(object sender, EventArgs e)
        {
            _currentPage = 1;
            LoadRegistrationData();
        }
        
        /// <summary>
        /// 卡号文本框回车事件
        /// </summary>
        private void TxtCardNo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                BtnSearch_Click(sender, e);
                e.Handled = true;
            }
        }
        
        /// <summary>
        /// 上一页按钮点击事件
        /// </summary>
        private void BtnPrevPage_Click(object sender, EventArgs e)
        {
            if (_currentPage > 1)
            {
                _currentPage--;
                LoadRegistrationData();
            }
        }
        
        /// <summary>
        /// 下一页按钮点击事件
        /// </summary>
        private void BtnNextPage_Click(object sender, EventArgs e)
        {
            if (_currentPage < _totalPages)
            {
                _currentPage++;
                LoadRegistrationData();
            }
        }
        
        /// <summary>
        /// DataGridView选择改变事件
        /// </summary>
        private void DgvRegistrations_SelectionChanged(object sender, EventArgs e)
        {
            btnSelect.Enabled = dgvRegistrations.SelectedRows.Count > 0;
        }
        
        /// <summary>
        /// DataGridView双击事件
        /// </summary>
        private void DgvRegistrations_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                BtnSelect_Click(sender, e);
            }
        }
        
        /// <summary>
        /// 选择按钮点击事件
        /// </summary>
        private void BtnSelect_Click(object sender, EventArgs e)
        {
            if (dgvRegistrations.SelectedRows.Count > 0)
            {
                var selectedRow = dgvRegistrations.SelectedRows[0];
                SelectedRegistration = selectedRow.DataBoundItem as RegistrationDto;
                
                if (SelectedRegistration != null)
                {
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
            }
        }
        
        /// <summary>
        /// 取消按钮点击事件
        /// </summary>
        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
        
        /// <summary>
        /// 窗体关闭事件
        /// </summary>
        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            // 释放HTTP客户端资源
            _httpClient?.Dispose();
            base.OnFormClosed(e);
        }
        #endregion
    }
    
    #region 数据模型类
    /// <summary>
    /// 挂号记录DTO
    /// </summary>
    public class RegistrationDto
    {
        /// <summary>
        /// 挂号记录ID
        /// </summary>
        public long Id { get; set; }
        
        /// <summary>
        /// 患者ID
        /// </summary>
        public long PatientId { get; set; }
        
        /// <summary>
        /// 挂单号
        /// </summary>
        public string RegistrationNo { get; set; } = string.Empty;
        
        /// <summary>
        /// 医疗卡号
        /// </summary>
        public string CardNo { get; set; } = string.Empty;
        
        /// <summary>
        /// 患者姓名
        /// </summary>
        public string PatientName { get; set; } = string.Empty;
        
        /// <summary>
        /// 号类
        /// </summary>
        public string RegistrationType { get; set; } = string.Empty;
        
        /// <summary>
        /// 挂单费
        /// </summary>
        public decimal RegistrationFee { get; set; }
        
        /// <summary>
        /// 其他费用
        /// </summary>
        public decimal OtherFee { get; set; }
        
        /// <summary>
        /// 科室
        /// </summary>
        public string Department { get; set; } = string.Empty;
        
        /// <summary>
        /// 医师
        /// </summary>
        public string Doctor { get; set; } = string.Empty;
        
        /// <summary>
        /// 挂单日期
        /// </summary>
        public DateTime RegistrationDate { get; set; }
        
        /// <summary>
        /// 就诊日期
        /// </summary>
        public DateTime VisitDate { get; set; }
        
        /// <summary>
        /// 状态
        /// </summary>
        public string Status { get; set; } = string.Empty;
        
        /// <summary>
        /// 是否启用
        /// </summary>
        public bool IsEnable { get; set; }
    }
    
    /// <summary>
    /// API分页返回结果
    /// 与后端APIPaging<T>结构匹配
    /// </summary>
    public class ApiPagingResult<T>
    {
        /// <summary>
        /// 返回码
        /// </summary>
        public int Code { get; set; }
        
        /// <summary>
        /// 返回消息
        /// </summary>
        public string Msg { get; set; } = string.Empty;
        
        /// <summary>
        /// 分页数据列表
        /// </summary>
        public List<T>? PageDatas { get; set; }
        
        /// <summary>
        /// 总记录数
        /// </summary>
        public int TotalCount { get; set; }
    }
    #endregion
}